<template>
  <div class="chat-header">
    <el-image
      v-if="chatType === 1"
      class="chat-header-avatar"
      :src="uploadAvatar"
      fit="fill"
      v-user="userId"
    />
    <div class="chat-header-user" :style="{ 'left': chatType === 2 ? '20px' : '60px' }">
      <span class="chat-header-user-name" @click="handleModifyName">{{chatForm.name}}</span>
      <!-- <span class="chat-header-user-phone">18888888888</span> -->
    </div>
    <el-popover
      v-if="chatType === 2"
      placement="top"
      width='360'
      popper-class="group-info"
      trigger="click"
      @show="handleShow"
      @hide="handleHide"
    >
      <div class="popover-header">
        <el-upload
          class="upload-img"
          action="string"
          :before-upload="onBeforeUploadImage"
          :http-request="uploadImagePic"
          :show-file-list="false"
          accept=".jpg,.jpeg,.png"
        >
          <img :src="uploadAvatar">
          <div>
            <i class="iconfont icon-camera"></i>
          </div>
        </el-upload>
        <div class="popover-title">
          <template v-if="!isEdit">
            <span>{{ chatForm.name }}</span>
            <i class="iconfont icon-edit-square1" @click="handleModifyName"></i>
          </template>
          <el-form
            v-else
            class="chat-form"
            ref="chatFormRef"
            label-position="top"
            :model="chatForm"
            :rules="rules"
            @submit.native.prevent
          >
            <el-form-item prop="name">
              <el-input
                v-model="chatForm.name"
                ref="inputRef"
                :placeholder="$t('common.base.tip.defaultPlaceholder')"
                maxlength="50"
                style="width: 240px;"
                @blur="handleBlur"
              ></el-input>
              <!-- <i class="iconfont icon-duihao1" @click="updatePortalName"></i>
              <i class="iconfont icon-close" @click="isEdit = false"></i> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="popover-main">
        <div>
          {{$t('common.notification.teamMember')}}： <span>{{ $t('system.internalCoordination.text5', {count: memberUserList.length}) }}</span>
        </div>
        <div class="popover-main-member">
          <div v-for="(item, index) of memberUserList" :key="index">
            <i
              v-if="index !== 0 && isGroupLeader"
              class="iconfont icon-butongyi"
              @click="handleDelete(index)"
            ></i>
            <img :src="item.memberUserHead" alt="" />
            <span>{{ item.memberUserName }}</span>
          </div>
          <div>
            <i class="iconfont icon-add" @click="showPop"></i>
          </div>
        </div>
      </div>
      <div class="popover-footer">
        <div @click="handleExitGroupChat">
          <i class="iconfont icon-comment"></i>
          <span>{{$t('common.notification.quitGroupChat')}}</span>
        </div>
        <div @click="handleUngroup" v-if="isGroupLeader">
          <i class="iconfont icon-fenzu"></i>
          <span>{{$t('common.notification.dissolveTheGroup')}}</span>
        </div>
      </div>
      <i class="iconfont icon-xitongguanli" slot="reference" v-track="$track.formatParams('SET_UP_TEAM_CHAT')"></i>
    </el-popover>
    <i class="iconfont icon-right1" @click="closeChat"></i>
  </div>
</template>

<script>
import { getOssUrl } from '@src/util/assets'
const head_customer = getOssUrl('/avatar.png')
import Uploader from 'packages/BaseUpload/uploader'
import {
  editMemberUser,
  signOut,
  dissolution,
  getGroupChatDetails,
  editGroupChatInfo,
} from '@src/api/ImApi.js';
import { getRootWindowInitData } from '@src/util/window'

import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser'
import { getAttachmentIdByUrl, deleteServerFiles } from 'pub-bbx-utils'
export default {
  name: 'chat-header',
  computed:{
    userId(){
      return this.chatParams?.chatOtherUserId ?? ''
    },
    chatType() {
      return this.chatParams?.chatType ?? 1
    },
    memberUserList() {
      return this.groupChatDetails?.memberUserList ?? []
    },
    loginUser() {
      return getRootWindowInitData().user
    },
    isGroupLeader() {
      return this.loginUser?.userId === this.memberUserList[0]?.memberUserId
    },
  },
  props: {
    chatParams: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      uploadAvatar: '',
      groupName: '',
      isEdit: false,
      chatForm: {
        name: '',
      },
      rules: {
        name: [
          { required: true, message: this.$t('system.internalCoordination.text6'), trigger: 'change' },
          { max: 50, message: this.$t('common.base.tip.maxCharacterTip', {num: '50'}), trigger: 'change' },
        ],
      },
      groupChatDetails: {}
    };
  },
  watch: {
    chatParams: {
      immediate: true,
      deep: true,
      handler(newValue, _) {
        this.uploadAvatar = newValue?.chatTitleHead ?? head_customer;
        this.chatForm.name = newValue?.chatTitleName ?? ''
      }
    }
  },
  methods: {
    closeChat(){
      this.$eventBus.$emit('closeChat')
    },
    handleShow() {
      this.getGroupChatDetails();
    },
    handleHide() {
      if (this.chatForm.name === '') this.chatForm.name = this.chatParams?.chatTitleName;
      
      setTimeout(() => {
        this.isEdit = false;
      }, 1000)
    },
    handleUpdateGroupInfo(obj) {
      const params = {
        chatUuid: this.chatParams?.chatUuid,
        groupName: this.chatParams?.chatTitleName,
        groupHead: this.chatParams?.chatTitleHead,
      }
      params[obj.key] = obj.val;
      this.editGroupChatInfo(params);
    },
    // 变更群聊基本信息：群名称、头像等
    async editGroupChatInfo(params) {
      try {
        const { code, message } = await editGroupChatInfo(params)
        if (code !== 0) this.$message.error(message);

        this.$eventBus.$emit('getChatList');
      } catch (error) {
        console.error(error)
      }
    },
    // 获取群聊详情
    async getGroupChatDetails() {
      try {
        const { code, message, data } = await getGroupChatDetails({
          groupUuid: this.chatParams?.chatUuid,
        });
        if (code !== 0) this.$message.error(message);

        this.groupChatDetails = data;
      } catch (error) {
        console.error(error);
      }
    },
    handleUpdateMember() {
      this.getGroupChatDetails();
      this.$eventBus.$emit('getChatList');
    },
    handleModifyName() {
      this.isEdit = true;
      this.$nextTick(()=>{
        this.$refs.inputRef.$el.querySelector('input').focus();
      })
      this.$track.clickStat(this.$track.formatParams('MODIFY_TEAM_NAME'))
    },
    handleBlur() {
      this.$refs.chatFormRef.validate().then((validated) => {
        if (!validated) return;

        this.isEdit = false;
        this.handleUpdateGroupInfo({ key: 'groupName', val: this.chatForm.name });
      })
    },
    onBeforeUploadImage (file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      
      if (!isJPG) {
        this.$message.error(this.$t('product.productType.tips.tip24'));
      }
      if (!isLt2M) {
        this.$message.error(this.$t('system.internalCoordination.text7', {num1: '2'}));
      }
      
      return isJPG && isLt2M;
    },
    uploadImagePic(param) {
      Uploader.upload(param.file, '/files/upload')
        .then((result) => {
          if (result.status != 0) {
            this.$message({
              message: `${result.message}`,
              duration: 1500,
              type: 'error',
            });
            return;
          }
          
          let file = result.data;
          let item = {
            uid: param.file.uid,
            id: file.id,
            filename: file.fileName,
            // 如果后端返回url,必须使用。如果后端不返回，需要拼接
            url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
            fileSize: file.fileSizeStr,
          }
          // 删除老的头像
          const oldAvatarId = getAttachmentIdByUrl(this.uploadAvatar);
          oldAvatarId && deleteServerFiles([oldAvatarId])
          
          this.uploadAvatar = item.url;
          this.handleUpdateGroupInfo({ key: 'groupHead', val: this.uploadAvatar });
        })
        .catch((err) => {
          console.warn(err)
        })
        .finally(() => { 
          // 
        })
    },
    showPop() {
      // 打开选人弹窗
      const newMember = this.memberUserList.map(v => {
        return {
          userId: v.memberUserId,
          displayName: v.memberUserName
        }
      })
      let options = {
        title: this.$t('system.notificationCenter.text6'),
        min: 1,
        max: 10,
        selected: newMember,
        mode: BaseSelectUserModeEnum.Filter
      };
      
      /** 
       * FIXME: 选人组件
      */
      this.$fast.select.multi.user(options).then((result = {}) => {
        if(result.status == 0){
          let data = result.data || {};
          let users = data.users || [];
          // this.activeUser = users[0]
          // this.singleChat(users[0].userId)
          const userList = users.map(v => {
            return {
              userId: v.userId,
              displayName: v.displayName,
            }
          })
          this.editMemberUser(userList)
        }
      })
        .catch(err => console.error(err))
      this.$track.clickStat(this.$track.formatParams('ADD_TEAM_MEMBERS'))
    },
    handleDelete(index) {
      const userList = this.memberUserList
        .map(v => {
          return {
            userId: v.memberUserId,
            displayName: v.memberUserName,
          };
        })
        .filter((_, i) => i !== index);
      this.editMemberUser(userList);
    },
    async editMemberUser(userList) {
      try {
        const { code, message } = await editMemberUser({
          chatUuid: this.chatParams?.chatUuid,
          userList
        });
        if (code !== 0) this.$message.error(message);
        
        this.handleUpdateMember();
      } catch (error) {
        console.error(error);
      }
    },
    handleExitGroupChat() {
      this.$confirm(this.$t('common.notification.tips.tip1'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(async () => {
        try {
          const { code, message } = await signOut({
            chatUuid: this.chatParams?.chatUuid,
          });
          if (code !== 0) this.$message.error(message);
          this.closeChat();
          this.$eventBus.$emit('getChatList');

          this.$message({
            type: 'success',
            message: this.$t('system.internalCoordination.text8')
          });
        } catch (error) {
          console.error(error);
        }
      }).catch(() => {});
      this.$track.clickStat(this.$track.formatParams('QUIT_TEAM_CHAT'))
    },
    handleUngroup() {
      this.$confirm(this.$t('common.notification.tips.tip2'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(async () => {
        try {
          const { code, message } = await dissolution({
            chatUuid: this.chatParams?.chatUuid,
          });
          if (code !== 0) this.$message.error(message);
          this.closeChat();
          this.$eventBus.$emit('getChatList');

          this.$message({
            type: 'success',
            message: this.$t('system.internalCoordination.text9')
          });
        } catch (error) {
          console.error(error);
        }
      }).catch(() => {});
      this.$track.clickStat(this.$track.formatParams('DISSOLVE_TEAM'))
    }
  },
};
</script>

<style scoped lang="scss">
.chat-header {
  width: 100%;
  height: 40px;
  border-bottom: 1px solid #e8e8e8;
  position: relative;

  &-avatar {
    position: absolute;
    left: 16px;
    top: 3px;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    cursor: pointer;
  }

  &-user {
    position: absolute;
    left: 60px;
    top: 10px;
    width: 300px;
    &-name {
      font-size: 14px;
      color: #000000;
      font-weight: bold;
      @include text-ellipsis;
      // width: 100%;
      width: 200px;
      display: inline-block;
    }

    &-phone {
      font-size: 12px;
      color: #8c8c8c;
      margin-left: 4px;
    }
  }

  &-department {
    position: absolute;
    left: 60px;
    top: 27px;
    font-size: 12px;
    color: #8c8c8c;
  }
  .icon-xitongguanli {
    position: absolute;
    right: 50px;
    top: 10px;
    cursor: pointer;
    font-size: 14px;
  }

  .icon-right1{
    position: absolute;
    right: 20px;
    top: 10px;
    cursor: pointer;
    font-size: 14px;
  }

  .icon-right1:hover,
  .icon-xitongguanli:hover {
    color: $color-primary-light-6;
  }
}

.group-info {
  width: 360px;
  // height: 285px !important;
  background: #fafafa;
  border-radius: 0px 0px 8px 8px;
  padding: 0 !important;

  .popover-header {
    width: 100%;
    height: 93px;
    display: flex;
    align-items: center;

    .upload-img {
      width: 50px;
      height: 50px;
      position: relative;
      margin: 0 21px;

      img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }

      div {
        display: none;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background: rgba(0, 0, 0, 0.5);
        position: absolute;
        top: 0;
        left: 0;
        text-align: center;
        line-height: 50px;

        i {
          font-size: 14px;
          color: #fff;
        }
      }
    }

    .upload-img:hover {
      div {
        display: block;
      }
    }

    .popover-title {
      width: 230px;
      font-size: 16px;
      font-weight: 500;
      color: #000000;
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        width: 180px;
        height: 22px;
        @include text-ellipsis;
      }

      i {
        font-size: 16px;
        cursor: pointer;
      }
    }
  }

  .popover-main {
    // height: 217px;
    height: auto;
    background: #FAFAFA;
    font-size: 14px;
    color: #8C8C8C;
    padding: 17px 21px;

    span {
      color: #262626;
    }

    &-member {
      display: flex;
      flex-wrap: wrap;
      margin-top: 10px;

      div {
        max-width: 40px;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 14px 14px 0 14px;
        position: relative;

        .icon-butongyi {
          display: none;
          position: absolute;
          right: -4px;
          top: -4px;
          cursor: pointer;
          color: #8C8C8C;
        }

        img {
          width: 40px;
          height: 40px;
          border-radius: 20px;
          margin-bottom: 4px;
        }

        span {
          width: 40px;
          text-align: center;
          font-size: 12px;
          color: #8C8C8C;
          @include text-ellipsis;
        }
      }

      div:hover  {
        .icon-butongyi {
          display: block;
        }
      }

      div:nth-child(5n + 1) {
        margin-left: 0;
      }

      div:nth-child(5n) {
        margin-right: 0;
      }

      div:last-child {
        width: 40px;
        height: 40px;
        border-radius: 20px;
        background: #FFFFFF;
        border: 1px solid rgba(5,26,19,0.1000);
        cursor: pointer;

        .icon-add {
          font-size: 20px;
          color: #8C8C8C;
        }
      }
    }
  }

  .popover-footer {
    height: 68px;
    background: #F5F5F5;
    display: flex;
    align-items: center;
    padding-left: 20px;

    div {
      display: flex;
      flex-direction: column;
      align-items: center;
      font-size: 12px;
      color: #FF4D4F;
      margin-right: 30px;
      cursor: pointer;

      i {
        margin-bottom: 4px;
        font-size: 15px;
        color: #FF4D4F;
      }
    }
  }
}
</style>
